'use client'

import { useState } from "react"
import { PencilIcon, TrashIcon } from "@heroicons/react/24/outline"
import { EditIncomeDialog } from "./edit-income-dialog"
import { deleteIncome } from "@/actions/income"
import { SerializedFinanceRecord } from "@/types"

interface IncomeItemProps {
  record: SerializedFinanceRecord
}

export function IncomeItem({ record }: IncomeItemProps) {
  const [isEditOpen, setIsEditOpen] = useState(false)
  const [submitting, setSubmitting] = useState(false)

  const handleDelete = async () => {
    if (!confirm('确定要删除此收入记录吗？')) return

    try {
      setSubmitting(true)
      const result = await deleteIncome(record.id)
      if (!result.success) {
        alert(result.error)
      }
    } catch (error) {
      console.error('删除收入记录失败:', error)
      alert('删除收入记录失败')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <tr className="hover:bg-gray-50">
      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-green-600">
        +¥{parseFloat(record.amount).toFixed(2)}
      </td>
      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
        {record.description}
      </td>
      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
        {new Date(record.createdAt).toLocaleString()}
      </td>
      <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
        <button
          onClick={() => setIsEditOpen(true)}
          className="text-indigo-600 hover:text-indigo-900 mr-4"
        >
          <PencilIcon className="h-5 w-5" />
        </button>
        <button
          onClick={handleDelete}
          disabled={submitting}
          className="text-red-600 hover:text-red-900 disabled:opacity-50"
        >
          <TrashIcon className="h-5 w-5" />
        </button>
        {isEditOpen && (
          <EditIncomeDialog
            record={record}
            open={isEditOpen}
            onClose={() => setIsEditOpen(false)}
          />
        )}
      </td>
    </tr>
  )
} 